<template>
  <el-card class="box_card">
    <el-form
      class="manage_form"
      ref="manageformRef"
      :model="manageForm"
      :rules="manageRules"
      label-width="110px"
    >
      <el-form-item label="管理员名称：" prop="manageName">
        <el-input v-model="manageForm.manageName"></el-input>
      </el-form-item>
      <el-form-item label="管理员账号：" prop="managePhone">
        <el-input v-model="manageForm.managePhone"></el-input>
      </el-form-item>
      <el-form-item label="管理员密码：" prop="passWord">
        <el-input v-model="manageForm.passWord"></el-input>
      </el-form-item>

      <el-form-item label="管理员状态：">
        <el-switch v-model="manageForm.manageStatus" />
      </el-form-item>
      <el-form-item label="管理员权限："></el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          v-if="!manageForm.id"
          @click="submitmanageForm('add')"
        >
          添加管理员
        </el-button>
        <el-button type="primary" v-else @click="submitmanageForm('modify')">
          修改管理员
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { addManageApi, findManageApi, updateManageApi } from '@/api/manage'
import { useRoute, useRouter } from 'vue-router'

import { ElForm, ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

onMounted(() => {
  findManage()
})
// 查找管理员的详细信息
const findManage = async () => {
  if (route.query.id) {
    let res: any = await findManageApi(route.query.id)
    manageForm.manageName = res.data.manageName
    manageForm.managePhone = res.data.managePhone
    manageForm.manageStatus = res.data.manageStatus
    manageForm.passWord = res.data.passWord
    manageForm.id = res.data.id
  }
}
// 管理员表单
let manageForm = reactive({
  manageName: '', // 管理员名称
  managePhone: '', // 管理员账号
  manageStatus: true, // 管理员账号状态
  passWord: '', // 登录密码
  id: '', // 管理员id
})
const manageRules = reactive({
  manageName: [
    {
      required: true,
      message: '请输入管理员名称',
      trigger: 'blur',
    },
  ],
  managePhone: [
    {
      required: true,
      message: '请输入管理员账号',
      trigger: 'blur',
    },
  ],
  passWord: [
    {
      required: true,
      message: '请输入管理员登录密码',
      trigger: 'blur',
    },
  ],
})
const manageformRef: any = ref<InstanceType<typeof ElForm>>()
const submitmanageForm = (type: string) => {
  manageformRef.value.validate(async (valid: any) => {
    if (valid) {
      let requst = null
      if (type == 'add') {
        requst = addManageApi
      } else {
        requst = updateManageApi
      }
      let res: any = await requst(manageForm)
      if (res.status == 0) {
        ElMessage.success(`${type == 'add' ? '添加' : '修改'}管理员成功`)
        router.go(-1)
      }
    }
  })
}
</script>
<style lang="scss" scoped>
.box_card {
  margin: $mainMargin;

  .manage_form {
    width: 300px;
  }
}
</style>
